import {PerspectiveCamera, Scene, WebGLRenderer} from "three"
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
import Stats from 'stats-js'

export default (function () {
    const [cFov, cAspect, cNear, cFar] = [70, window.innerWidth / window.innerHeight, 0.01, 2000]
    const DEBUG = true

    const mScene = new Scene()
    const mStats = new Stats()
    const mRenderer = new WebGLRenderer({antialias: true})
    const mCamera = new PerspectiveCamera(cFov, cAspect, cNear, cFar)
    const mControl = new OrbitControls(mCamera, mRenderer.domElement)

    let preRender = () => { }
    let postRender = () => { }

    const animate = () => {
        mStats.begin()
        if (preRender != null) preRender()
        mRenderer.render(mScene, mCamera)
        if (postRender != null) postRender()
        mStats.end()
    }

    const onResize = () => {
        mCamera.aspect = window.innerWidth / window.innerHeight
        mCamera.updateProjectionMatrix()
        mRenderer.setSize(window.innerWidth, window.innerHeight)
    }

    mRenderer.physicallyCorrectLights = true
    mRenderer.setAnimationLoop(animate)
    mRenderer.setSize(window.innerWidth, window.innerHeight)
    window.addEventListener("resize", onResize)


    const renderTo = (domElement) => {
        if (domElement instanceof HTMLElement) {
            domElement.appendChild(mRenderer.domElement)

            if (DEBUG) {
                mStats.dom.style.left = null
                mStats.dom.style.right = 0
                domElement.appendChild(mStats.dom)
            }
        } else console.warn("[engine] Render to dom failed.")
    }

    console.log("[engine] 实例化完成")

    return { mRenderer, mScene, mCamera, mControl, renderTo, preRender, postRender }
})()

